package cn.edu.wynu.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Component
@ComponentScan
@Configuration
@PropertySource("jdbc.properties")
@EnableTransactionManagement // 开启声明式事务
public class JdbcConfiguration {
    @Value("${jdbc.url}")
    String jdbcUrl;

    @Value("${jdbc.username}")
    String jdbcUsername;

    @Value("${jdbc.password}")
    String jdbcPassword;

    @Value("${jdbc.driver}")
    String jdbcDriver;

    @Bean
    DriverManagerDataSource createDataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUrl(jdbcUrl);
        driverManagerDataSource.setUsername(jdbcUsername);
        driverManagerDataSource.setPassword(jdbcPassword);
        driverManagerDataSource.setDriverClassName(jdbcDriver);
        return driverManagerDataSource;
    }

    @Bean
    JdbcTemplate createJdbcTemplate(@Autowired DriverManagerDataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    /**
     * 创建事务管理器
     * @param dataSource 数据源
     * @return 事务管理器
     */
    @Bean
    PlatformTransactionManager createTransactionManager(@Autowired DriverManagerDataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}
